package com.csun.nusing.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.FollowDeviceSearchBloodPressJsonBean;
import com.csun.nusing.bean.jsonbean.FollowDeviceSearchBloodPressJsonBean.FollowDeviceSearchBloodPressDataBean;
import com.csun.nusing.bean.jsonbean.FollowDeviceSearchBloodPressJsonBean.FollowDeviceSearchBloodPressDataBean.BpressureListBean;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.myview.DoubleTimerPickerDialog;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.ToastUtil;
import com.csun.ttfutil.TTFSdk;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;
import com.linktop.whealthService.HealthApi;
import com.linktop.whealthService.HealthApi.BleCallBack;
import com.linktop.whealthService.HealthApi.EcgCallBack;
import com.linktop.whealthService.HealthApi.HealthApiCallBack;
import com.linktop.whealthService.OnBLEService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * 血压测试的主界面 ClassName: BloodPressTestActivity
 *
 * @author fzq
 * @Description: TODO
 * @date 2017-10-25
 */
public class BloodPressMainActivity extends BaseActivity<CommonPresenter>
        implements IBase {

    private LineChartView line_chart;
    private LinearLayout picll;
    private LinearLayout datall;
    private ListView datelv;
    private TextView historydatetv;
    private TextView pictv;
    private TextView datetv;
    private ImageView measure_iv;
    private TextView choosetv;
    private TextView timepick_tv;
    //
    private List<String> Xdate = new ArrayList<String>();
    private List<Integer> score = new ArrayList<Integer>();
    private List<Integer> score2 = new ArrayList<Integer>();

    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<PointValue> mPoint2Values = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    public Intent intent;
    private Calendar calendar;
    private int year;
    private int month;
    private int day;
    private int hour = 10;
    private int min = 25;
    private int mendhour = 10;
    private int mendMin = 25;
    private ArrayList<Line> lines;
    private Axis axisY;
    private Axis axisX;
    private String olderId = "";
    private String authorization;
    protected FollowDeviceSearchBloodPressJsonBean searchBloodPressJsonBean;
    private TextView bpmaxtv;
    private TextView bpmintv;
    private TextView statetv;
    private TextView suggesttv;
    private List<BpressureListBean> datalist = new ArrayList<BpressureListBean>();
    protected String startdaytime = "";
    protected String enddaytime = "";
    private LineChartData data;
    private LineChartData data2;
    private Line line;
    private Line line2;
    private RelativeLayout navrl;
    private boolean isFamily;
    private int nowyear;
    private int nowmonth;
    private int nowday;
    private boolean bleOn;
    private String deviceMacAddress;
    private HealthApi mHealthApi;
    private Timer batteryQueryTimer;
    private static final int REQUEST_BLUETOOTH_DEVICE = 0;// 蓝牙连接
    private static final int REQUEST_OPEN_BT = 2;

    @Override
    public int getContentViewId() {
        return R.layout.activity_blood_press_test;
    }

    @Override
    public void initSubViews(View view) {
        super.initSubViews(view);
        /**
         * find控件
         */
        initView();
    }

    @Override
    public void initData() {
        super.initData();
        olderId = getIntent().getStringExtra("olderId");
        isFamily = getIntent().getBooleanExtra("isFamily", false);
        deviceMacAddress = getIntent().getStringExtra("deviceMacAddress");
        bleOn = getIntent().getBooleanExtra("bleOn", false);
        if (isFamily) {
            navrl.setBackgroundResource(R.drawable.main_whiteyello_color_shape);
        }
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        nowyear = year;
        nowmonth = month;
        nowday = day;
        timepick_tv.setText("1" + getString(R.string.month) + "1" + getString(R.string.day) + "-" + nowmonth + getString(R.string.month) + nowday + getString(R.string.day));
        /**
         * 获取血压数据
         */
        getBloodPressData();
        mHealthApi = new HealthApi();
        mHealthApi.init(getApplicationContext(), new healthapicallback(),
                mbpHandler, mbtHandler, moxHandler, mbsHandler,
                new ecgcallback());
        mHealthApi.setBleCallBack(new blecallback());

    }

    private class healthapicallback implements HealthApiCallBack {
        @Override
        public void healthCallBack(int type, Object data) {
        }
    }

    private class ecgcallback implements EcgCallBack {
        @Override
        public void onReceive(int[] data) {
        }
    }

    private Handler mbtHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        }

    };
    @SuppressLint("HandlerLeak")
    private Handler moxHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler mbpHandler = new Handler() {
        public void handleMessage(Message msg) {
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler mbsHandler = new Handler() {
        public void handleMessage(Message msg) {
        }

    };

    private class blecallback implements BleCallBack {
        @Override
        public void bleCallBack(int type, Object data) {
            if (type == HealthApi.BLE_STATUS) {
                setBleUiState((Integer) data);
            }
        }
    }

    private void modual_init() {
        mHealthApi.ecgQuery();
        mHealthApi.bsQuery();
        mHealthApi.batteryQuery();

        if (batteryQueryTimer == null)
            batteryQueryTimer = new Timer();
        batteryQueryTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHealthApi.batteryQuery();
            }
        }, 300000, 300000);
    }

    private void setBleUiState(int mState) {
        switch (mState) {
            case OnBLEService.BLE_CONNECTED:
                break;
            case OnBLEService.BLE_DISCONNECTED:
                break;
            case OnBLEService.BLE_NOTIFICATION_ENABLED:
                modual_init();
                break;
            case OnBLEService.BLE_NOTIFICATION_NOTENABLED:
                break;
            default:
                break;
        }
    }

    /**
     * 获取血压数据
     */
    private void getBloodPressData() {
        authorization = (String) SPUtils.get(this, "authorization", "");
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("oldmanId", olderId);
        OkHttpTask.newInstance(this).addHeader("authorization", authorization)
                .post(param, OkType.form).enqueue(new IOkTaskCallback() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                if (result != null) {
                    searchBloodPressJsonBean = gson.fromJson(result,
                            FollowDeviceSearchBloodPressJsonBean.class);
                    if (searchBloodPressJsonBean != null) {
                        if (searchBloodPressJsonBean.getData() != null) {
                            controlSearchDate(searchBloodPressJsonBean
                                    .getData());
                        } else {
                            ToastUtil.showMessage(
                                    getApplicationContext(),R.string.no_data);
                        }
                    }
                }
            }
        }).start(UrlBean.SEARCHBPRESSRELATIONURL);

    }

    /**
     * 处理数据
     *
     * @param @param data
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-31
     */
    protected void controlSearchDate(FollowDeviceSearchBloodPressDataBean data) {
        bpmaxtv.setText("" + data.getMAX() + "mmHg");
        bpmintv.setText("" + data.getMIN() + "mmHg");
        statetv.setText("" + data.getStatus());
        suggesttv.setText("" + data.getSuggest());
        datalist = data.getBpressureList();
        for (int i = 0; i < datalist.size(); i++) {
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
            Date date = new Date(datalist.get(i).getCreateTime());
            Xdate.add(sdf.format(date));
            score.add(datalist.get(i).getDbp());
            score2.add(datalist.get(i).getSbp());
        }
        initDate();
    }

    /**
     * 獲取數據,展示數據 图表展示
     *
     * @param
     * @return void
     * @throws
     * @Description:
     * @author fzq
     * @date 2017-10-10
     */
    private void initDate() {
        getAxisXLables();// 获取x轴的标注
        getAxisPoints();// 获取坐标点
        getBxisPoints();// 获取第二条线的点
        initLineChart();// 初始化
        addLinetwo();// 添加另一条线
        showlv();// 展示lv的数据
    }

    private void addLinetwo() {
        line2 = new Line(mPoint2Values);
        line2.setColor(Color.WHITE); // 折线的颜色
        line2.setShape(ValueShape.CIRCLE);// 折线图上每个数据点的形状 这里是圆形 （有三种
        // ：ValueShape.SQUARE
        // ValueShape.CIRCLE
        // ValueShape.SQUARE）
        line2.setCubic(false);// 曲线是否平滑
        line2.setStrokeWidth(2);// 线条的粗细，默认是3
        line2.setFilled(false);// 是否填充曲线的面积
        line2.setHasLabels(true);// 曲线的数据坐标是否加上备注
        line2.setHasLines(true);// 是否用直线显示。如果为false 则没有曲线只有点显示
        line2.setHasPoints(true);// 是否显示圆点 如果为false 则没有原点只有点显示

        lines.add(line2);
        data2 = new LineChartData();
        data2.setLines(lines);
        data2.setAxisXBottom(axisX); // x 轴在底部
        data2.setAxisYLeft(axisY); // Y轴设置在左边
        data2.setBaseValue(Float.NEGATIVE_INFINITY);
        line_chart.setLineChartData(data2);

    }

    private void showlv() {

    }

    /**
     * 点击事件监听
     *
     * @param
     * @return void
     * @throws
     * @Description:
     * @author fzq
     * @date 2017-10-11
     */
    private void initView() {
        navrl = findViewById(R.id.nav_rl);
        measure_iv = findViewById(R.id.bloodpresstest_measure_iv);
        line_chart = findViewById(R.id.bloodpresstest_line_chart);
        picll = findViewById(R.id.bloodpresstest_pic_ll);
        datall = findViewById(R.id.bloodpresstest_data_ll);
        datelv = findViewById(R.id.bloodpresstest_date_lv);
        historydatetv = findViewById(R.id.bloodpresstest_historydata_tv);
        pictv = findViewById(R.id.bloodpresstest_pic_tv);
        choosetv = findViewById(R.id.bloodpresstest_time_choose_tv);
        datetv = findViewById(R.id.bloodpresstest_date_tv);
        timepick_tv = findViewById(R.id.bloodpresstest_timepick_tv);
        bpmaxtv = findViewById(R.id.bloodpresstest_bpmax_tv);
        bpmintv = findViewById(R.id.bloodpresstest_bpmin_tv);
        statetv = findViewById(R.id.bloodpresstest_state_tv);
        suggesttv = findViewById(R.id.bloodpresstest_suggest_tv);

        measure_iv.setOnClickListener(new click());
        historydatetv.setOnClickListener(new click());
        pictv.setOnClickListener(new click());
        datetv.setOnClickListener(new click());
        choosetv.setOnClickListener(new click());
        timepick_tv.setOnClickListener(new click());
    }

    /**
     * 初始化LineChart的一些设置
     *
     * @param
     * @return void
     * @throws
     * @Description: chart设置
     * @author fzq
     * @date 2017-10-10
     */
    private void initLineChart() {
        line = new Line(mPointValues);
        line.setColor(Color.WHITE); // 折线的颜色
        lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);// 折线图上每个数据点的形状 这里是圆形 （有三种
        // ：ValueShape.SQUARE
        // ValueShape.CIRCLE
        // ValueShape.SQUARE）
        line.setCubic(false);// 曲线是否平滑
        line.setStrokeWidth(2);// 线条的粗细，默认是3
        line.setFilled(false);// 是否填充曲线的面积
        line.setHasLabels(true);// 曲线的数据坐标是否加上备注
        // line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);// 是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);// 是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        data = new LineChartData();
        data.setLines(lines);

        // 坐标轴
        axisX = new Axis(); // X轴
        axisX.setHasTiltedLabels(false); // X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.WHITE); // 设置字体颜色
        // axisX.setTextColor(Color.parseColor("#D6D6D9"));//灰色
        // 坐标轴颜色
        axisX.setLineColor(Color.TRANSPARENT);
        // axisX.setName("未来几天的天气"); //表格名称
        axisX.setTextSize(10);// 设置字体大小
        axisX.setMaxLabelChars(7); // 最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(mAxisXValues); // 填充X轴的坐标名称
        data.setAxisXBottom(axisX); // x 轴在底部
        // data.setAxisXTop(axisX); //x 轴在顶部
        axisX.setHasLines(true); // x 轴分割线

        axisY = new Axis(); // Y轴
        axisY.setName("");// y轴标注
        axisY.setTextSize(11);// 设置字体大小
        data.setAxisYLeft(axisY); // Y轴设置在左边
        axisY.setLineColor(Color.TRANSPARENT);
        axisY.setTextColor(Color.WHITE);
        // data.setAxisYRight(axisY); //y轴设置在右边
        // 设置行为属性，支持缩放、滑动以及平移
        line_chart.setInteractive(true);
        // 设置能否缩放
        line_chart.setZoomEnabled(true);
        line_chart.setZoomType(ZoomType.HORIZONTAL); // 缩放类型，水平
        line_chart.setMaxZoom((float) 3);// 缩放比例
        line_chart.setLineChartData(data);
        line_chart.setVisibility(View.VISIBLE);
        /**
         * 注：下面的7，10只是代表一个数字去类比而已
         * 尼玛搞的老子好辛苦！！！见（http://forum.xda-developers.com/tools
         * /programming/library-hellocharts-charting-library-t2904456/page2）;
         * 下面几句可以设置X轴数据的显示个数
         * （x轴0-7个数据），当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。当数据点个数大于（29）的时候，
         * 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
         * 若设置axisX.setMaxLabelChars(int count)这句话, 33个数据点测试，若
         * axisX.setMaxLabelChars(10);里面的10大于v.right= 7; 里面的7，则
         * 刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10 若小于v.right=
         * 7;中的7,反正我感觉是这两句都好像失效了的样子 - -! 并且Y轴是根据数据的大小自动设置Y轴上限 若这儿不设置 v.right= 7;
         * 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差
         */
        Viewport v = new Viewport(line_chart.getMaximumViewport());
        v.left = 0;
        // 设置当前显示多少数据
        v.right = 8;
        line_chart.setCurrentViewport(v);
    }

    /**
     * X 轴的显示
     */
    private void getAxisXLables() {
        for (int i = 0; i < Xdate.size(); i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(Xdate.get(i)));
        }
    }

    /**
     * 图表的每个点的显示
     */
    private void getAxisPoints() {
        for (int i = 0; i < score.size(); i++) {
            mPointValues.add(new PointValue(i, score.get(i)));
        }
    }

    private void getBxisPoints() {
        for (int i = 0; i < score2.size(); i++) {
            mPoint2Values.add(new PointValue(i, score2.get(i)));
        }
    }

    /**
     * 点击事件处理 ClassName: click
     *
     * @author fzq
     * @Description: TODO
     * @date 2017-10-10
     */
    private class click implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bloodpresstest_measure_iv:
                    // 跳转测量界面
                    if (bleOn) {
                        intent = new Intent(BloodPressMainActivity.this,
                                BloodPressMessureActivity.class);
                        intent.putExtra("olderId", olderId);
                        intent.putExtra("isFamily", isFamily);
                        startActivityForResult(intent, 0x11);
                    } else {
                        searchDevice();
                    }
                    break;
                case R.id.bloodpresstest_historydata_tv:
                    // 跳转温度历史记录界面
                    intent = new Intent(BloodPressMainActivity.this,
                            BloodPressHistoryActivity.class);
                    intent.putExtra("olderId", olderId);
                    intent.putExtra("isFamily", isFamily);
                    startActivity(intent);
                    break;
                case R.id.bloodpresstest_pic_tv:
                    picll.setVisibility(View.VISIBLE);
                    datall.setVisibility(View.GONE);

                    break;
                case R.id.bloodpresstest_date_tv:
                    picll.setVisibility(View.GONE);
                    datall.setVisibility(View.VISIBLE);

                    break;
                case R.id.bloodpresstest_time_choose_tv:
                    chooseTime();
                    break;
                case R.id.bloodpresstest_timepick_tv:
                    chooseDay();
                    break;
            }
        }
    }

    /**
     * 搜索蓝牙设备
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-10
     */
    public void searchDevice() {
        if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            if (!bleOn) {// mState != BLE_DISCONNECTED
                Intent intent = new Intent(BloodPressMainActivity.this,
                        FollowDeviceSearchActivity.class);
                if (deviceMacAddress != null && deviceMacAddress.length() > 4) {
                } else {
                    ToastUtil.showMessage(getApplicationContext(),
                            "请选择搜索到的随访仪设备");
                }
                intent.putExtra("deviceMacAddress", "" + deviceMacAddress);
                intent.putExtra("isFamily", isFamily);
                startActivityForResult(intent, REQUEST_BLUETOOTH_DEVICE);
            } else {
                // 断开设备蓝牙
                mHealthApi.bleDisconnect();
                bleOn = false;
                ToastUtil.showMessage(this, R.string.ble_is_un_relative);
            }
        } else {
            enableBluetooth();
        }
    }

    /**
     * 打开手机蓝牙
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-10
     */
    private void enableBluetooth() {
        BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
        if (bta == null) {
            Toast.makeText(this, R.string.not_support_ble, Toast.LENGTH_SHORT).show();
        } else {
            if (!bta.isEnabled()) {
                startActivityForResult(new Intent(
                                "android.bluetooth.adapter.action.REQUEST_ENABLE"),
                        REQUEST_OPEN_BT);
            }
        }
    }

    /**
     * 筛选时间
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-11
     */
    public void chooseTime() {
        new DoubleTimerPickerDialog(this,
                android.R.style.Theme_DeviceDefault_Light_Dialog,
                new DoubleTimerPickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(TimePicker startDatePicker,
                                          int starthour, int startMin,
                                          TimePicker endDatePicker, int endhour, int endMin) {
                        hour = starthour;
                        min = startMin;
                        mendhour = endhour;
                        mendMin = endMin;
                        if (mendhour < hour) {
                            mendhour = hour;
                        }
                        startdaytime = year + "-" + (month + 1) + "-" + day
                                + " " + hour + ":" + min + ":00";
                        enddaytime = nowyear + "-" + nowmonth + "-" + nowday
                                + " " + mendhour + ":" + mendMin + ":00";
                        choosetv.setText(getString(R.string.timess) + starthour + getString(R.string.time)+"-" + endhour
                                + getString(R.string.time));
                        refreashData();
                    }
                }, hour, min, mendhour, mendMin).show();
    }

    /**
     * 选择日期
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-11
     */
    private void chooseDay() {

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                /**
                 * 保存设置的时间
                 */
                month = monthOfYear;
                day = dayOfMonth;
                String textString = String.format("%d月%d日",
                        monthOfYear + 1, dayOfMonth);
                timepick_tv.setText(textString + "-" + nowmonth + "月"
                        + nowday + "日");
                // 2017-10-30 10:30:00
                startdaytime = year + "-" + (monthOfYear + 1) + "-"
                        + dayOfMonth + " " + hour + ":" + min + ":00";
                enddaytime = nowyear + "-" + nowmonth + "-" + nowday
                        + " " + mendhour + ":" + mendMin + ":00";
                // 刷新数据
                refreashData();
            }
        }, year, month, day);

        datePickerDialog.setCancelable(true);
        DatePicker dp = datePickerDialog.getDatePicker();
        dp.setMaxDate(calendar.getTimeInMillis());
        datePickerDialog.show();
    }

    /**
     * 刷新数据
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-11
     */
    private void refreashData() {
        /**
         * 获取血压数据
         */
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("oldmanId", olderId);
        param.put("startTime", startdaytime);
        param.put("endTime", enddaytime);
        OkHttpTask.newInstance(this).addHeader("authorization", authorization)
                .post(param, OkType.form).enqueue(new IOkTaskCallback() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                if (result != null) {
                    searchBloodPressJsonBean = gson.fromJson(result,
                            FollowDeviceSearchBloodPressJsonBean.class);
                    if (searchBloodPressJsonBean != null) {
                        if (searchBloodPressJsonBean.getData() != null) {
                            // 删除表
                            deleteData();
                            controlSearchDate(searchBloodPressJsonBean
                                    .getData());
                        }
                    }
                }
            }
        }).start(UrlBean.SEARCHBPRESSRELATIONURL);
    }

    protected void deleteData() {
        Xdate = new ArrayList<String>();
        score = new ArrayList<Integer>();
        score2 = new ArrayList<Integer>();
        mPointValues = new ArrayList<PointValue>();
        mPoint2Values = new ArrayList<PointValue>();
        mAxisXValues = new ArrayList<AxisValue>();
        data.getLines().clear();
        data2.getLines().clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        refreashData();
        switch (requestCode) {
            case REQUEST_BLUETOOTH_DEVICE:
                if (resultCode == RESULT_OK) {
                    String strAddress = data.getExtras().getString(
                            BluetoothDevice.EXTRA_DEVICE);
                    bleOn = true;
                    if (!mHealthApi.bleConnect(strAddress)) {
                        Log.e("fzq", "connect error");
                        bleOn = false;
                        // finish();
                    } else {
                        // mySyntherizer.speak("随访仪连接成功");
                        TTFSdk.speak(mSpeechSynthesizer,getString(R.string.follow_is_relative));
                        intent = new Intent(BloodPressMainActivity.this,
                                BloodPressMessureActivity.class);
                        intent.putExtra("olderId", olderId);
                        intent.putExtra("isFamily", isFamily);
                        startActivityForResult(intent, 0x11);
                    }
                } else {
                    // bluetoothIv.setImageResource(R.drawable.bluetooth);
                }
                break;
            case REQUEST_OPEN_BT:
                if (resultCode == RESULT_OK) {
                } else {
                }
                break;
        }
    }

    /**
     * 对back键的点击做判断，如果按back键，默认退回到主页面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent intent = new Intent();
            intent.putExtra("bleOn", bleOn);
            setResult(0x22, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 监听返回键
    public void OnBACK(View view) {
        Intent intent = new Intent();
        intent.putExtra("bleOn", bleOn);
        setResult(0x22, intent);
        finish();
    }

}
